package quartz.demo.util;

import org.quartz.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class QuartzUtil {

    @Resource
    private Scheduler scheduler;


    /**
    * @Description: 删除定时任务
    * @Date: 2023-04-17 16:02:53
    * @Author: 陈文波
    */
    public void schedulerDelete(String code) {
        try {
            scheduler.pauseTrigger(TriggerKey.triggerKey(code));
            scheduler.unscheduleJob(TriggerKey.triggerKey(code));
            scheduler.deleteJob(JobKey.jobKey(code));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("删除定时任务失败");
        }
    }

    /**
    * @Description: 添加定时任务
    * @Date: 2023-04-17 16:03:01
    * @Author: 陈文波
    */
    public void schedulerAdd(String code, String jobClassName, String cronExpression, String parameter) {
        try {
            // 启动调度器
            scheduler.start();

            // 构建job信息
            JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(code).usingJobData("parameter", parameter).build();

            // 表达式调度构建器(即任务执行的时间)
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(code).withSchedule(scheduleBuilder).build();

            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            throw new RuntimeException("创建定时任务失败", e);
        } catch (RuntimeException e) {
            throw new RuntimeException(e.getMessage(), e);
        }catch (Exception e) {
            throw new RuntimeException("后台找不到该类名：" + jobClassName, e);
        }
    }

    /**
    * @Description: 反射获取实现类对象
    * @Date: 2023-04-17 16:03:12
    * @Author: 陈文波
    */
    public static Job getClass(String classname) throws Exception {
        Class<?> class1 = Class.forName(classname);
        return (Job) class1.newInstance();
    }

}
